package com.ktjy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjy.pojo.Customer;
import com.ktjy.pojo.Dict;
import com.ktjy.pojo.SysUser;
import com.ktjy.service.ICustomerService;
import com.ktjy.service.IDictService;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jjx
 * @since 2025-01-15
 */
@Controller
@RequestMapping("/customer")
public class CustomerController {
    Logger logger = LoggerFactory.getLogger(LinkmanController.class);

    @Autowired
    ICustomerService iCustomerService;
    @Autowired
    IDictService iDictService;

    @RequestMapping("/list")
    public String list(Customer customer,
                       @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                       HttpSession session,
                       Model model) {
        try {
            //组装分页条件
            Page<Customer> page=new Page<>(pageIndex,pageSize);
            //组装过滤条件 动态sql
            QueryWrapper<Customer> qw=new QueryWrapper();
            if(customer.getCustName()!=null && !customer.getCustName().equals("")){
                qw.like("cust_name",customer.getCustName());
            }
            if(customer.getCustNo()!=null && !customer.getCustNo().equals("")){
                qw.eq("cust_no",customer.getCustNo());
            }
            if(customer.getCustRegion()!=null && !customer.getCustRegion().equals("")){
                qw.eq("cust_region",customer.getCustRegion());
            }
            if(customer.getCustManagerName()!=null && !customer.getCustManagerName().equals("")){
                qw.like("cust_manager_name",customer.getCustManagerName());
            }
            if(customer.getCustLevel()!=null){
                qw.eq("cust_level",customer.getCustLevel());
            }
            //客户经理只查自己创建的客户数据
            SysUser sysUser=(SysUser)session.getAttribute("loginUser");
            if(sysUser.getUsrRoleId()==2){//客户经理
                qw.eq("cust_manager_id",sysUser.getUsrId());
            }
            //调用分页方法
            IPage<Customer> pager=iCustomerService.page(page, qw);
            model.addAttribute("pager", pager);

            //回显数据
            model.addAttribute("condition", customer);

            //查询客户等级
            QueryWrapper qw2 = new QueryWrapper();
            qw2.eq("dict_type", "客户等级");
            List<Dict> levelList = iDictService.list(qw2);
            model.addAttribute("levelList", levelList);
            //查询地区
            QueryWrapper qw3 = new QueryWrapper();
            qw3.eq("dict_type", "地区");
            List<Dict> regionList = iDictService.list(qw3);
            model.addAttribute("regionList", regionList);
        } catch (Exception e) {
            logger.error("CustomerController 中的 list 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "customer/list";
    }

    /**
     * 跳转修改页面
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/edit")
    public String edit(@RequestParam("id") String id, Model model) {
        try {
            //根据客户编号，查询客户信息
            Customer customer = iCustomerService.getById(id);
            model.addAttribute("customer", customer);

            //查询客户等级
            QueryWrapper qw = new QueryWrapper();
            qw.eq("dict_type", "客户等级");
            List<Dict> levelList = iDictService.list(qw);
            model.addAttribute("levelList", levelList);

            //查询地区
            QueryWrapper qw2 = new QueryWrapper();
            qw2.eq("dict_type", "地区");
            List<Dict> regionList = iDictService.list(qw2);
            model.addAttribute("regionList", regionList);
        } catch (Exception e) {
            logger.error("CustomerController 中的 toEdit 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "customer/edit";
    }

    @PostMapping("/update")
    public String update(Customer customer) {
        try {
            boolean ok = iCustomerService.updateById(customer);
            if (ok) {
                //跳转到列表;重定向到分页方法
                return "redirect:/customer/list";
            } else {
                //跳回新增页面
                return "customer/edit";
            }
        } catch (Exception e) {
            logger.error("CustomerController 中的 update 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
    }


    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Object del(@PathVariable("id") String id) {
        Map<String, Object> map = new HashMap<>();
        try {
            boolean ok = iCustomerService.removeById(id);  //调用service的方法进行数据删除
            if (ok) {
                map.put("delResult", true);
            } else {
                map.put("delResult", false);
            }
        } catch (Exception e) {
            logger.error("CustomerController 中的 del 方法执行发生错误。", e);
            map.put("delResult", false);
        }
        return map;
    }
}
